<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Video Chat</title>
</head>
<body>
    <h1>Realtime communication with WebRTC</h1>

    <video id="localVideo" autoplay></video>
    <video id="remoteVideo" autoplay></video>

</body>

<script src="./js/adapter.js"></script>
<script src="./js/sockjs.min.js"></script>
<script src="./js/stomp.js"></script>
<script src="./js/jquery-3.1.1.js"></script>
<script type="text/javascript">
    'use strict';
    var isCaller = window.location.href.split('#')[1];

    // 与信令服务器的WebSocket连接
    var socket = new SockJS('/rtc-video-chat/endpointSang');
    var stompClient = Stomp.over(socket);


    var startTime;
    var localVideo = document.getElementById('localVideo');
    var remoteVideo = document.getElementById('remoteVideo');

    localVideo.addEventListener('loadedmetadata', function() {
        trace('Local video videoWidth: ' + this.videoWidth +
                'px,  videoHeight: ' + this.videoHeight + 'px');
    });

    remoteVideo.addEventListener('loadedmetadata', function() {
        trace('Remote video videoWidth: ' + this.videoWidth +
                'px,  videoHeight: ' + this.videoHeight + 'px');
    });

    var iceServers = null;
    window.peerConn = new RTCPeerConnection(iceServers);
    if (peerConn) (function () {
        console.log("浏览器支持实时音频通讯");
    })();else {
        console.log("您使用的浏览器暂不支持实时音频通讯。");
    }

    stompClient.connect({}, function (frame) {
        console.log('============ Connected:' + frame);
        stompClient.subscribe('/topic/signalling', function(event){
            var body = event.body;
            console.log("Receive Message Body : " , body);

            var json = JSON.parse(body);
            //如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
            if( json.event === "_ice_candidate" ){
                console.log('candidate : ' , json.data.candidate);
                peerConn.addIceCandidate(new RTCIceCandidate(json.data.candidate));
            } else {
                peerConn.setRemoteDescription(new RTCSessionDescription(json.data.sdp));
                // 如果是一个offer，那么需要回复一个answer
                if(json.event === "_offer") {
                    peerConn.createAnswer(sendAnswerFn, function (error) {
                        console.log('Failure callback: ' + error);
                    });
                }
            }
        })
    });

    // 发送offer的函数
    var sendOfferFn = function (desc) {
        console.log('send offer : ' , desc);
        // 设置本地Offer
        peerConn.setLocalDescription(desc);
        // 发送offer
        stompClient.send("/video-chat" , {}, JSON.stringify({
            "event": "_offer",
            "data": {
                "sdp": desc
            }
        }));
    };

    // 发送answer的函数，发送本地session描述
    var sendAnswerFn = function(desc){ // 发送answer
        console.log('send answer : ' , desc);
        peerConn.setLocalDescription(desc); // 设置本地Offer
        stompClient.send("/video-chat" , {}, JSON.stringify({ // 发送answer
            "event": "_answer",
            "data": {
                "sdp": desc
            }
        }));
    };

    navigator.getUserMedia = navigator.getUserMedia ||
            navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
    var constraints = {
        audio: true,
        video: true
    };

    // 发布本地视频流
    navigator.getUserMedia(constraints, successCallback, errorCallback);

    function successCallback(stream) {
        console.log('local successCallback stream : ' , stream);
        peerConn.addStream(stream);
        if (window.URL) {
            localVideo.src = window.URL.createObjectURL(stream);
        } else {
            localVideo.src = stream;
        }
        if(isCaller){
            peerConn.createOffer(sendOfferFn, function (error) {
                console.log('createOffer Failure callback: ' + error);
            });
        } else {
            peerConn.createAnswer(sendAnswerFn , function (error) {
                console.log('createAnswer Failure callback: ' + error);
            })
        }
    };

    function errorCallback(error) {
        console.log('navigator.getUserMedia error: ', error);
    }

    // 发送ICE候选到其他客户端
    peerConn.onicecandidate = function(event){
        if (event.candidate !== null) {
            stompClient.send("/video-chat" , {}, JSON.stringify({
                "event": "_ice_candidate",
                "data": {
                    "candidate": event.candidate
                }
            }));
        }
    };

    // 如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
    peerConn.onaddstream = function(event){
        remoteVideo.src = URL.createObjectURL(event.stream);
    };

    function trace(text) {
        if (text[text.length - 1] === '\n') {
            text = text.substring(0, text.length - 1);
        }
        if (window.performance) {
            var now = (window.performance.now() / 1000).toFixed(3);
            console.log(now + ': ' + text);
        } else {
            console.log(text);
        }
    }

</script>
</html>